//
//  LBVignetteFilter.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 4/5/13.
//  Copyright (c) 2013 UIT. All rights reserved.
//

#include "LBVignetteFilter.h"
#include "LBGraphics.h"

char fShaderStrVignette[] = ""

"   precision mediump float;  "
"   uniform sampler2D texture; "
"   varying vec2 vtexCoor; "

"   uniform float start;"
"   uniform float end;"
"   uniform vec3 vignetteColor;"
"   uniform vec2 center;"

"   void main(){  "
"       lowp vec4 textureColor = texture2D(texture,vtexCoor);"
"       float alpha = textureColor.a;"
"       lowp float d = distance(vtexCoor, center);"
"       float percent = smoothstep(start, end, d);"
"       gl_FragColor = vec4(mix(textureColor.x, vignetteColor.x, percent), mix(textureColor.y, vignetteColor.y, percent), mix(textureColor.z, vignetteColor.z, percent), alpha);"
"   }  "
"";

LBVignetteFilter::LBVignetteFilter(){
    init(0, fShaderStrVignette);
    LBGraphics::getInstance()->useProgram(program);
    startUniform = program->uniformIndex("start");
    endUniform = program->uniformIndex("end");
    vignetteColorUniform= program->uniformIndex("vignetteColor");
    centerUniform = program->uniformIndex("center");
    
    setStart(0.3);
    setEnd(0.75);
    setCenter(0.5, 0.5);
    setVignetteColor(0.0, 0.0, 0.0);
}

void LBVignetteFilter::setStart(float start){
    this->start = start;
    LBGraphics::getInstance()->useProgram(program);
    glUniform1f(startUniform, start);
}

void LBVignetteFilter::setEnd(float end){
    this->end = end;
    LBGraphics::getInstance()->useProgram(program);
    glUniform1f(endUniform, end);
}

void LBVignetteFilter::setCenter(float x, float y){
    center[0] = x;
    center[1] = y;
    LBGraphics::getInstance()->useProgram(program);
    glUniform2f(centerUniform, x, y);
}

void LBVignetteFilter::setVignetteColor(float r, float g, float b){
    vignetteColor[0] = r;
    vignetteColor[1] = g;
    vignetteColor[2] = b;
    LBGraphics::getInstance()->useProgram(program);
    glUniform3f(centerUniform, r, g, b);
}